package ram;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Machine {
	
	private static RAM ram = new RAM();
	
	private static final int DEFAULT_RAM_SIZE = 8196;

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String mFile = null;
		String pFile = null;
		int memSize = DEFAULT_RAM_SIZE;
		
		int pFileArgIndex = 0;
		int mFileArgIndex = 1;
		
		if( args.length > 1 && args[0].equals("-m")) {
			pFileArgIndex += 2;
			mFileArgIndex += 2;
			try {
				memSize = Integer.parseInt(args[1]);
			} catch( NumberFormatException e ) {
				printUsage();
			}
		}
		
		if( args.length < mFileArgIndex ) {
			printUsage();
		}
		
		mFile = args[mFileArgIndex];
		pFile = args[pFileArgIndex];
		
		try {
			BufferedReader mReader = new BufferedReader( new FileReader( new File(mFile) ) );
			BufferedReader pReader = new BufferedReader( new FileReader( new File(pFile) ) );
			ram.init( pReader, mReader, memSize );
			
			System.out.println( "Initial Memory Configuration: " );
			ram.dump();
			
			ram.execute();
			
			System.out.println( "Final RAM configuration: " );
			ram.dump();
		} catch (FileNotFoundException e) {
			System.err.println( "Trouble running the machine." );
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println( "Trouble running the machine." );
			e.printStackTrace();
		}
	}

	private static void printUsage() {
		System.out.println( "Usage:" );
		System.out.println( "     java ram.Machine [-m memSize] progFile memFile ");
		System.exit(1);
	}

}
